/*
 * @lc app=leetcode id=236 lang=cpp
 *
 * [236] Lowest Common Ancestor of a Binary Tree
 */
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if (!root) {
            return root;
        }
        deque<TreeNode*> pathP, pathQ;
        findNodePath(root, p, pathP);
        findNodePath(root, q, pathQ);

        int pLen = pathP.size();
        int qLen = pathQ.size();

        int len = pLen < qLen ? pLen : qLen;

        TreeNode *prev = NULL;
        for (int i=0; i<len; i++) {
            if (pathP[i] != pathQ[i]) {
                break;
            } else {
                prev = pathP[i];
            }
        }
        return prev;
    }

    bool findNodePath(TreeNode* root, TreeNode *p, deque<TreeNode*> & path) {
        TreeNode *node = root;

        if (!node) {
            return false;
        }

        path.push_back(node);

        if (node->val == p->val) {
            return true;
        }

        if (findNodePath(node->left, p, path) || 
                findNodePath(node->right, p, path)) {
            return true;
        }

        path.pop_back();
        return false;
    }

};

